﻿using System;
using UnityEngine;
using UnityEngine.UIElements;
using winS.UnityEditor.UIElement;
using static winS.UnityEditor.ProcessEditor.ProcessEditorData;
using Button = winS.UnityEditor.UIElement.Button;
using DropdownMenu = winS.UnityEditor.UIElement.DropdownMenu;

namespace winS.UnityEditor.ProcessEditor
{
    public class History : VisualElement
    {
        public event Action onPing;
        public event Action<string> onOpen;

        private readonly Button button;
        private readonly Button dropdownButton;
        private readonly HistoryData historyData;
        private readonly DropdownMenu dropdownBox;

        internal History(HistoryData historyData)
        {
            this.historyData = historyData;
            historyData.onClear += OnHistoryClear;
            style.flexDirection = FlexDirection.Row;
            style.SetWidth(24f, LengthUnit.Percent);

            Add(button = EditorElementUtility.elementFactory.CreateButton(() => onPing?.Invoke()));
            button.label.style.unityTextAlign = TextAnchor.MiddleCenter;
            button.highlightColor = button.normalColor = new Color32(56, 56, 56, 255);
            button.style.flexGrow = 1f;
            button.style.SetBorderWdith(0f);

            Add(dropdownButton = EditorElementUtility.elementFactory.CreateButton(Resources.Load<Texture>("winS.UnityEditor.ProcessEditor/Icons/下拉"), () => dropdownBox.Show(this, layout.width)));
            dropdownButton.style.SetMargin(0f);
            dropdownButton.style.SetBorderWdith(0f);
            dropdownButton.normalColor = Color.clear;

            dropdownBox = new DropdownMenu(historyData.historyList, path => onOpen?.Invoke(path));
            dropdownBox.enableAdaptive = false;
        }

        public string GetRecentHistoryFilePath()
        {
            return historyData.historyList.Count != 0 ? historyData.historyList[0] : null;
        }

        public void SetCurrentFile(EditorProcessInfo editorProcessInfo)
        {
            int index = historyData.historyList.IndexOf(editorProcessInfo.pathRelativeProject);
            if (index != -1) historyData.historyList.RemoveAt(index);
            historyData.historyList.Insert(0, editorProcessInfo.pathRelativeProject);
            if (historyData.historyList.Count > historyData.maxHistory) historyData.historyList.RemoveAt(historyData.historyList.Count - 1);
            dropdownBox.Close();
            dropdownBox.Refresh();
            button.text = editorProcessInfo.name;
            editorProcessInfo.onUpdated += () => button.text = editorProcessInfo.name;
        }
        public void ClearCurrentFile()
        {
            button.text = string.Empty;
        }

        private void OnHistoryClear()
        {
            dropdownBox.Close();
            dropdownBox.Refresh();
        }
    }
}